package com.glzn.springboot03.controller;

import com.glzn.springboot03.entity.WaveHead;
import com.glzn.springboot03.service.WaveService;
import com.glzn.springboot03.util.VeDate;
import org.apache.logging.log4j.util.Base64Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Administrator
 */
@Controller
public class WaveController {
	@Autowired
	private WaveService waveService;

	private static final Logger logger = LoggerFactory.getLogger(EventController.class);

	@RequestMapping("/getwavehead")
	@ResponseBody
  public String getWaveHead(){
		return waveService.listWaveHead();
	}

	@GetMapping(value = "/getwavehead/getprocess")
	@ResponseBody
	public int getProcess(HttpSession session){
		return waveService.getProcess(session.getId());
	}

	@GetMapping(value = "/getwave/getprocess")
	@ResponseBody
	public int getprocess(HttpSession session){
		return waveService.getProcess(session.getId());
	}

	@RequestMapping("/waveheads")
	public String wavehead(ModelMap modelMap, HttpSession session, HttpServletResponse response) {
		Integer deviceId = (Integer) session.getAttribute("device_id");
		List<WaveHead> waveHeads = waveService.findAll(deviceId);
		modelMap.put("waveHeads", waveHeads);
		return "waveheads";
	}

	@RequestMapping("/wx/wavehead")
	@ResponseBody
	public List<WaveHead> wxWavehead(ModelMap modelMap, HttpServletResponse response, HttpSession session) {
		Integer deviceId = (Integer) session.getAttribute("device_id");
		return waveService.findAll(deviceId);
	}

	@RequestMapping("/getwave")
	@ResponseBody
	public String getWave(ModelMap modelMap,
	                      HttpSession session,
	                      HttpServletResponse response,
	                      @RequestParam(required = false,defaultValue = "0") List<Integer> id) throws UnsupportedEncodingException {
		Integer deviceId = (Integer) session.getAttribute("device_id");
		List<WaveHead> waveHeadList = new ArrayList<>();
		for (Integer id1 : id) {
			WaveHead waveHead = waveService.findById(id1, deviceId);
			waveHeadList.add(waveHead);
		}
		String result = waveService.listWave(waveHeadList);
		if ("failed".equals(result)){
			return "failed";
		}
		return "success";
	}

	@GetMapping("/download")
	@ResponseBody
	public String downloadWave(ModelMap modelMap,
	                           HttpSession session,
	                           HttpServletResponse response,
	                           @RequestParam(required = false,defaultValue = "0") List<Integer> id) throws UnsupportedEncodingException {
		Integer deviceId = (Integer) session.getAttribute("device_id");
		List<String> paths = new ArrayList<>();
		for (Integer id1 : id) {
			WaveHead waveHead = waveService.findById(id1, deviceId);
			String filepath = waveHead.getType() + "(" + VeDate.dateToStrLong(waveHead.getHappenTime()).replaceAll(":", "_") + "-" + waveHead.getMillsecond() + ").wave";
			paths.add(filepath);
		}
		downLoad(response, paths);
		return "success";
	}

	public void downLoad(HttpServletResponse response, List<String> paths){
		//设置zip文件的目录和文件名
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
		String zipFileName = "录波文件" + format.format(new Date()) + ".zip";

		ZipOutputStream zipOutputStream = null;
		FileInputStream fileInputStream = null;
		BufferedInputStream bufferedInputStream = null;
		File zipFile = new File(zipFileName);
		try {
			//构造压缩包的输出流
			zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
			for (String path : paths) {
				File file = new File(URLDecoder.decode(path, "UTF-8"));
				if (file.exists()) {
					fileInputStream = new FileInputStream(file);
					//压缩目录中文件的名字
					ZipEntry zipEntry = new ZipEntry(URLDecoder.decode(path, "UTF-8"));
					zipOutputStream.putNextEntry(zipEntry);
					bufferedInputStream = new BufferedInputStream(fileInputStream, 1024 * 10);

					int read = 0;
					byte[] buf = new byte[1024 * 10];
					while ((read = bufferedInputStream.read(buf, 0, 1024 * 10)) != -1) {
						zipOutputStream.write(buf, 0, read);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//关闭流
			try {
				if (null != bufferedInputStream){
					bufferedInputStream.close();
				}
				if (null != zipOutputStream){
					zipOutputStream.flush();
					zipOutputStream.close();
				}
				if (null != fileInputStream){
					fileInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (zipFile.exists()){
			downFile(response, zipFileName, zipFileName);
			zipFile.delete();
		}
	}

	/**
	 * 下载文件
	 * @param response 响应
	 * @param fileNme 文件名
	 * @param path 路径
	 */
	public void downFile(HttpServletResponse response, String fileNme, String path){
		if (fileNme != null){
			FileInputStream inputStream = null;
			BufferedInputStream bufferedInputStream = null;
			OutputStream outputStream = null;
			try {
				File file = new File(path);
				if (file.exists()){
					response.setHeader("Content-Type", "application/octet-stram");
					response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileNme, "UTF-8"));
					inputStream = new FileInputStream(file);
					bufferedInputStream = new BufferedInputStream(inputStream);
					outputStream = response.getOutputStream();

					byte[] buffer = new byte[1024];
					int len = 0;
					while ((len = bufferedInputStream.read(buffer)) != -1){
						outputStream.write(buffer, 0, len);
					}
				}else {
					String error = Base64Util.encode("下载的文件资源不存在");
					response.sendRedirect("/main.html");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if(inputStream != null){
						inputStream.close();
					}
					if (bufferedInputStream != null){
						bufferedInputStream.close();
					}
					if (outputStream != null){
						outputStream.flush();
						outputStream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
